<?php
namespace App\Admin\Controllers\System;

use App\Admin\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Admin\Admin;
use App\Admin\Models\Menu;
use App\Admin\Helper;

use App\Admin\Actions\Create;
use App\Admin\Actions\Update;
use App\Admin\Actions\Delete;

use App\Admin\Requests\System\MenuCreateRequest;
use App\Admin\Requests\System\MenuUpdateRequest;

class MenuController extends Controller
{
	use Update, Delete;

	public function modelName()
	{
		return Menu::class;
	}

	public function index(Request $request)
	{
		$query = Menu::query();

		if( $request->has('type') ){
			$query->where('type', $request->input('type'));
		}

		$models = $query->get();

		$tree = Helper::buildTree($models);

		return Admin::success($tree);
	}

	/**
	 * 新增菜单
	 */
	public function store(MenuCreateRequest $request)
	{
		$validated = $request->validated();
		$model = Menu::create($validated);

		if( $model && $request->has('buttons') ){
			$needButtons = $request->input('buttons');

			$buttons = $model->getButtons($needButtons);

			Menu::upsert($buttons, [], null);
		}


		return $model;
		return $validated;
	}



	// public function actionStore($setter)
	// {
	// 	$setter->validate([$this, 'validateRules']);
	// }


	public function actionUpdate($setter)
	{
		$setter->validate([$this, 'validateRules']);
	}

	public function validateRules($request)
	{
		return $request->validate([
			'parent_id' => 'sometimes|integer|min:0',
			'type'      => 'sometimes|in:M,B,L,I',
			'title'     => 'sometimes|string',
			'icon'      => 'sometimes|nullable|string',
			'name'      => 'sometimes|string',
			'path'      => 'sometimes|nullable|string',
			'component' => 'sometimes|nullable|string',

			'sort'      => 'sometimes|integer|between:0,10000',
			'is_hidden' => 'sometimes|integer|boolean',
		]);
	}


	public function destroy(Request $request, $id)
	{
		$model = Menu::findOrFail($id);

		$child = Menu::where('parent_id', $model->id)->count();
		abort_if($child!=0, 403, '菜单下有子菜单或者按钮，请先删除子菜单！');

		return Admin::success([
			'deleted' => $model->delete()
		]);
	}

	public function show(Request $request, $id)
	{
		$model = Menu::findOrFail($id);

		return Admin::success($model, 0, 'show');
	}



	public function tree(Request $request)
	{
		$format = $request->input('format');
		if( $format == '1' ){
			$models = Menu::where('type', 'M')->select(['id as value', 'parent_id', 'name as label'])->get();
		}elseif( $format == '2' ){
			$models = Menu::where('type', 'M')->select(['id', 'parent_id', 'name as title', 'id as key'])->get();
		}elseif( $format == '3' ){
			// 平铺树
			$models = Menu::where('type', 'M')->select(['id', 'parent_id', 'name'])->get();
			$tree = Admin::flattenTree($models->toArray());
			return $this->success($tree);

		}else{
			$models = Menu::where('type', 'M')->select(['id', 'parent_id', 'name'])->get();
		}

		return $this->success(
			Helper::buildTree($models)
		);
	}

	// http://www.llc.com/api/admin/system/menu/async
	public function async(Request $request)
	{
		$menuModels = Menu::where('type', 'M')->orderBy('sort')->get();

		$menuModels = $menuModels->map(function($menu){
			$data = [
				// 组树要用
				'id'          => $menu->id,
				'parent_id'   => $menu->parent_id,
				// 要返回的数据
				'name'        => $menu->code,      // 路由名称（必须保持唯一）
				'path'        => $menu->route,     // 前端路由路径
				'component'   => $menu->component, // 前端组件
				'redirect'    => $menu->redirect,  // 路由重定向（默认跳转地址）
			];

			if( $data['parent_id']==0 ){
				$data['meta'] = [
					'title'      => $menu->name,
					'icon'       => $menu->icon,         // 菜单图标
					'showLink'   => $menu->is_hidden==0, // 是否在菜单中显示
					'rank'       => 0,
				];

			}else{
				$data['meta'] = [
					'title'      => $menu->name,
					'icon'       => $menu->icon,         // 菜单图标
					'showLink'   => $menu->is_hidden==0, // 是否在菜单中显示
					'showParent' => ($menu->code=='Account') ? false : true,
				];
			}

			return $data;
		});

		$data = Helper::buildTree($menuModels, null, 'id', 'parent_id', function($item){
			unset($item['id']);
			unset($item['parent_id']);

			// if( !isset($item['children']) ){
			// 	$item['children'] = [];
			// }

			return $item;
		});

		return Admin::success($data);
	}

	// http://www.llc.com/api/admin/system/menu/nav
	public function nav()
	{
		$menuModels = Menu::where('type', 'M')->orderBy('sort')->get();

		$menuModels = $menuModels->map(function($menu){
			$data = [
				'id'          => $menu->id,
				'parent_id'   => $menu->parent_id,

				'title'       => $menu->title ,
				'name'        => empty($menu->name) ? Str::camel(str_replace('/', '_', $menu->component)) : $menu->name ,
				'path'        => empty($menu->path) ? '/'. $menu->component : $menu->path ,
				'component'   => $menu->component,
				'icon'        => $menu->icon ? $menu->icon : '',//$menu->icon
			];

			return $data;
		});

		$data = Helper::buildTree($menuModels, null, 'id', 'parent_id', function($item){
			unset($item['parent_id']);
			return $item;
		});

		return Admin::success($data);
	}
}
